<template>
  <div class="operationResult">
    <div v-if="gridTableData.length" class="displayFlex align-items-center">
      <el-tabs v-model="gridTabName" class="tighten-tabs flex1" @tab-click="gridTabClick">
        <el-tab-pane v-for="(grid, gridIndex) in gridTableData" :key="'gridIndex' + gridIndex" :name="gridIndex + ''">
          <template #label>
            <span>
              <el-tooltip effect="dark" :content="grid.description" placement="top" :disabled="!grid.description"
                :open-delay="500">
                <span>{{ grid.label }}</span>
              </el-tooltip>
            </span>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div ref="gridTableContainer" class="grid-table-tabs-container">
      <el-tabs v-if="gridTabTableData.length" v-model="gridTabTableName" tab-position="left"
        @tab-click="gridTabTableClick">
        <el-tab-pane v-for="(grid, gridIndex) in gridTabTableData" :key="'gridTableIndex' + gridIndex"
          :name="gridIndex + ''">
          <template #label>
            <span>
              <el-tooltip effect="dark" :content="grid.description" placement="right" :disabled="!grid.description"
                :open-delay="500">
                <span>{{ grid.label }}</span>
              </el-tooltip>
            </span>
          </template>
        </el-tab-pane>
      </el-tabs>
      <div class="grid-table-container"
        :style="{ width: (gridTableWidth && gridTabTableData.length) ? (gridTableWidth + 'px') : '100%' }">
        <div class="resultBox row" v-if="fileArr.length > 0 && (nodeStatus == 'success' || nodeStatus == 'failed')">
          <div class="fileNameList">
            <div class="fileBox" @click="fileClick(fileItem.value, false)" v-for="(fileItem, index) in fileArr"
              :key="index">{{
                fileItem.value }}
            </div>
          </div>
          <div class="contentBox">
            <box-loading v-if="logLoading" />
            <!-- <div class="downFile">
              <el-icon style="vertical-align: middle;margin-top: -2px;margin-right: 2px; font-size: 18px;cursor: pointer;">
                <Download />
              </el-icon>运行结果文件
            </div> -->
            <el-table :data="tableData" style="width: 100%" v-if="fileType == 'csv' && tableData.length > 0">
              <el-table-column v-for="(item, index) in tableName" :key="index" :prop="item" :label="item" />
            </el-table>
            <div class="downloadFile" v-if="fileType == 'csv' && tableData.length > 49"
              @click.stop="fileClick(fileName, true)">
              数据量过大，完整内容请下载
              <el-icon style="vertical-align: middle;margin-top: -2px;font-size: 20px;cursor: pointer;">
                <Download />
              </el-icon>
            </div>
            <iframe class="htmlBox" v-if="fileType == 'html' && fileHtml.length > 0" :srcdoc="fileHtml"></iframe>
          </div>
        </div>
        <div v-else style="margin:0 auto;">暂无运行结果</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue"
import { designerStore } from 'src/stores/designerTool/designerTool'
import { ElMessage } from 'element-plus'
import { getlogs } from 'src/api/designerTool'
import boxLoading from 'src/components/boxLoading.vue'
import dagGraph from 'src/pages/designerTool/canvas/DagEdit/graph/index.js'
import { useRouter } from 'vue-router';
import { index } from "@antv/x6/lib/util/dom/elem"
const router = useRouter()
const store = designerStore()
const props = defineProps({
  idConfig: {
    type: Object
  }
})
const gridTableData = ref(<any>[])
const gridTabName = ref('')
const gridTabTableName = ref('')
const gridTableWidth = ref(0)
const gridTableContainer = ref(null)
const logData = ref('')
const logLoading = ref(false)
const tableData = ref(<any>[])
const tableName = ref(<any>[])
const fileHtml = ref('')
const fileType = ref('')
const nodeStatus = ref('')
const node = ref<any>(null)
const fileArr = ref(<any>[])
const workflow_id = ref()
const instance_id = ref()
const fileName = ref('')
const gridTabIndex = computed(() => {
  return gridTabName.value ? parseInt(gridTabName.value) : -1
})
const gridTabTableData = computed(() => {
  return (gridTabIndex.value > -1 && gridTableData.value.length)
    ? gridTableData.value[gridTabIndex.value].ui_type === 'tab' ? gridTableData.value[gridTabIndex.value].tableData : []
    : []
})
function init(reaultObj: object) {
  instance_id.value = store.instanceId
  workflow_id.value = store.workflow_id
  if (store.LeftTabsState == false && store.experiments_id.workflow_id > 0 && router.currentRoute.value.name != 'canvas-index') {
    exprimentResult(reaultObj)
  } else {
    getInstancesLog()
  }
}

function getInstancesLog() {
  node.value = dagGraph.graph?.getCellById(store.selectedId).data
  fileType.value = ''
  tableData.value = []
  logData.value = ''
  nodeStatus.value = node.value.status.toLowerCase()
  fileArr.value = node.value.configs.filter((item: any) => {
    return item.param_type == 'output' || item.param_type == 'artifact'
  })
}
function exprimentResult(reaultObj: any = {}) {
  nodeStatus.value = reaultObj.status
  fileArr.value = JSON.parse(reaultObj.resultStr).filter((item: any) => {
    return item.param_type == 'output' || item.param_type == 'artifact'
  })
}
function fileClick(fileStr: string, type: boolean) {
  fileName.value = fileStr
  if (fileName.value.indexOf('.') > 0) {
    fileType.value = fileName.value.substring(fileName.value.lastIndexOf(".") + 1)
  }
  if (nodeStatus.value != 'success') {
    if (nodeStatus.value == 'failed') {
      ElMessage.error('该算子运行失败')
    } else {
      ElMessage.warning('该算子未运行完成')
    }
    return
  }
  logLoading.value = true
  if (store.LeftTabsState == false && store.experiments_id.workflow_id > 0) {
    workflow_id.value = store.experiments_id.workflow_id
    instance_id.value = store.experiments_id.id
  }
  getlogs(store.project_id, workflow_id.value, instance_id.value, {
    filepath: fileName.value,
    filetype: 'data'
  }).then((res: any) => {
    if (fileType.value == 'csv') {
      if (type) {
        downResultFile(res)
      } else {
        tableData.value = dataTidy(res.data)
        tableName.value = Object.keys(tableData.value[0])
      }

    }
    else if (fileType.value == 'html') {
      fileHtml.value = res.data
    }
    else {
      downResultFile(res)
    }
    logLoading.value = false
  }).catch(() => {
    logLoading.value = false
  })
}
function downResultFile(res: any) {
  let blob = new Blob([res.data], { type: 'application/octet-stream' });
  let downloadElement = document.createElement('a');
  let href = window.URL.createObjectURL(blob);
  downloadElement.href = href;
  downloadElement.download = decodeURI(res.headers.filename);
  document.body.appendChild(downloadElement);
  downloadElement.click();
  document.body.removeChild(downloadElement);
  window.URL.revokeObjectURL(href);
}

// 处理csv数据，以表格形式展示
function dataTidy(str: string) {
  let newArr = str.split('\n')
  let newObj = []
  for (let i = 0; i < newArr.length; i++) {
    let eleArr = newArr[i].split(',')
    let obj: any = {}
    let titleArr = newArr[0].split(',')
    if (i > 0) {
      titleArr.forEach((item, itemIndex) => {
        obj[item] = eleArr[itemIndex]
      })
    }
    if (i < 52) {
      newObj.push(obj)
    } else {
      break
    }
  }
  newObj.shift()
  newObj.pop()
  return newObj
}
defineExpose({ init })
</script>

<style lang="scss" scoped>
.operationResult {
  height: 100%;

  .el-tabs {
    margin-bottom: 6px;
  }

  .grid-table-tabs-container {
    height: calc(100% - 39px);

    ::v-deep .el-tabs {
      display: inline-block;
      vertical-align: top;

      .el-tabs__item {
        padding: 0 20px 0 0;
      }
    }

    .grid-table-container {
      vertical-align: top;
      display: inline-block;
      width: 100%;
      height: 100%;
    }
  }

  .button-group {
    margin-left: 10px;
  }
}

.resultBox {
  height: 100%;

  .fileNameList {
    width: calc(15% - 2px);
    border-right: 1px solid #eee;

    .fileBox {
      position: relative;
      width: 90%;
      padding: 0 22px 5px 2px;
      word-break: break-all;
      border-bottom: 1px solid #e2e2e2eb;
      margin-bottom: 5px;

      &:hover {
        cursor: pointer;
        border-bottom: 1px solid #3D5CE4;
        color: #3D5CE4;
      }

    }
  }

  .contentBox {
    width: 80%;
    position: relative;
  }

  .htmlBox {
    height: 100%;
    width: 100%;
    border: none;
  }

  .downFile {
    position: absolute;
    top: 0;
    right: -50px;
    z-index: 2;
  }

  .downloadFile {
    padding: 10px;

    &:hover {
      cursor: pointer;
      color: #3D5CE4;
    }
  }

}
</style>
